<?php
namespace app\common\controller;
use think\Controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class AliCloud extends Controller
{
     /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public function sendSms($tel,$tCode,$tParam){
        $config = \config('aliyun_sms'); //获取配置信息
        $accessKeyId = $config['KeyID'];//阿里云短信keyId
        $accessKeySecret = $config['KeySecret'];//阿里云短信keysecret
        $signName = $config['SignName'];
        $client = $this->createClient($accessKeyId, $accessKeySecret);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $tel,
            "signName" => $signName,
            "templateCode" => $tCode,
            "templateParam" => $tParam
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            return $res->body->code == 'OK' ? true : false;
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            Utils::assertAsString($error->message);
            return $error->message;
        }
    }


}